<?php

namespace App\Console\Commands;

use App\Models\ProxyUser;
use App\Models\User;
use App\Services\ProxyService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CreateProxyUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:createProxyUser';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '创建代理帐号';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(ProxyService $proxyService)
    {
        $users = User::where('id', '>', 100000)->where('total_traffic', '>', 0)->where('attempts', '<', 100)->get();
        foreach ($users as $user) {
            $exist = ProxyUser::where('user_id', $user->id)->first();
            if (!empty($exist) and $exist->status == 1) {
                continue;
            }
            $result = $proxyService->createProxyUser($user->id);
            if ($result['code'] !== 0) {
                $user->attempts = $user->attempts + 1;
                $user->save();
                Log::info('创建子帐号失败 user_id：' . $user->id . '，响应：' . json_encode($result, JSON_UNESCAPED_UNICODE));
            }
        }
        return true;
    }
}
